package com.nsl.my_youlai.mystar;

import com.nsl.my_youlai.mystar.enums.NslEnumMime;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;


import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

public class NslUtilHttpServletResponse {

    /**
     * 下载文件
     * @param response
     * @param file
     * @param enumMime
     * @throws UnsupportedEncodingException
     */
    public static void  downloadFile(HttpServletResponse response, File file, NslEnumMime enumMime) throws UnsupportedEncodingException {
       downloadFile(response,file,enumMime,file.getName());
    }

    public static void  downloadFile(HttpServletResponse response, File file, NslEnumMime enumMime,String fileName) throws UnsupportedEncodingException {
        fileName= URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType(enumMime.getValue());
        try (final ServletOutputStream outputStream = response.getOutputStream()){
            Files.copy(Paths.get(file.getPath()), outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
